import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router/index'

axios.defaults.headers.post['Content-Type'] = 'application/json'
const service = axios.create({
  baseURL: '',
  timeout: 30000
})

//请求前拦截
service.interceptors.request.use(
  (config) => {
    if (window.sessionStorage.getItem('token')) config.headers['token'] = window.sessionStorage.getItem('token')
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
//请求后（数据返回拦截）
service.interceptors.response.use(
  (config) => {
    const res = config.data
    if (res.code == 200) {
      return {
        code: res.code,
        data: res.data || null,
        msg: res.msg
      }
    } else if (res.code == 401) {
      //没有权限 则返回到登录页
      ElMessage.error('登录超时,请重新登录!')
      router.push({ name: 'Login' })
    }
  },
  (error) => {
    const erCode = error.message.replace(/[^0-9]/gi, '')
    if (erCode == 404) {
      ElMessage({
        message: '没有权限或请求地址错误！',
        type: 'error',
        duration: 2 * 1000
      })
    } else if (erCode == 'Unauthorized' || erCode == 401) {
      ElMessage({
        message: '登录超时，请重新登录',
        type: 'error',
        duration: 2 * 1000
      })
      router.push({ name: 'Login' })
    } else if (erCode == 500) {
      ElMessage({
        message: '系统内部异常，请稍后再试！',
        type: 'error',
        duration: 2 * 1000
      })
    } else {
      ElMessage({
        message: '服务超时，请稍后再试！',
        type: 'error',
        duration: 2 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
